package com.tedu.element.map;

import com.tedu.element.ElementObj;
import com.tedu.manager.GameLoad;
import com.tedu.show.GameConstants;

import javax.swing.*;
import java.awt.*;

public class MapObj extends ElementObj {
    // 绘制时的大小
    private int realW = GameConstants.TILE_SIZE;
    private int realH = GameConstants.TILE_SIZE;

    // 格子类型
    private TileType type;

    @Override
    public void showElement(Graphics g) {
        if (type == TileType.EMPTY) {
            return;
        }
        // 格子坐标
        int gridX = getGridX(), gridY = getGridY();
        // 切图格子坐标
        int dx = type.getDx(), dy = type.getDy();
        // 切图时的大小
        int boxSize = GameConstants.BOX_SIZE;

        // 处理高度为 2格的特殊对象（树、房屋）
        if (type.isTallObject()) {
            g.drawImage(getIcon().getImage(),
                    gridX * realW, (gridY - 1) * realH,
                    (gridX + 1) * realW, (gridY + 1) * realH,
                    dx * boxSize, dy * boxSize,
                    (dx + 1) * boxSize, (dy + 2) * boxSize,
                    null);
        } else {
            g.drawImage(getIcon().getImage(),
                    gridX * realW, gridY * realH,
                    (gridX + 1) * realW, (gridY + 1) * realH,
                    dx * boxSize, dy * boxSize,
                    (dx + 1) * boxSize, (dy + 1) * boxSize,
                    null);
        }
    }

    // str = "x,y,type"
    @Override
    public ElementObj createElement(String str) {
        String[] split = str.split(",");
        // 先确定格子类型
        this.type = GameLoad.fromCode(Integer.parseInt(split[2]));
        // 设置格子坐标
        this.setGridX(Integer.parseInt(split[0]));
        this.setGridY(Integer.parseInt(split[1]));
        // 根据类型获取图片
        ImageIcon icon = GameLoad.imgMap.get(this.type.getImageKey());
        assert icon != null;
        // 设置图片大小
        this.setW(icon.getIconWidth());
        this.setH(icon.getIconHeight());
        // 设置图片
        this.setIcon(icon);
        return this;
    }

    @Override
    public void setLive(boolean live) {
        // 判断是否无敌
        if (type.isInvincible()) {
            return;
        }
        super.setLive(live);
    }

    // 判断是否可通行
    public boolean isWalkable() {
        return type.isWalkable();
    }

    // 判断是否不可破坏
    public boolean isInvincible() {
        return type.isInvincible();
    }

    public void setType(TileType type) {
        this.type = type;
    }

    @Override
    public Rectangle getRectangle() {
        return new Rectangle(
                getX(),
                getY(),
                realW,
                realH
        );
    }

    public boolean isEmpty() {
        return type == TileType.EMPTY;
    }
}
